<template>
  <div style="margin-top: 20px">
    <div class="my-btn" >
      <a-button type="primary" @click="deployApplication">
        添加教研室
      </a-button>
    </div>
    <a-table :columns="columns"
             :data-source="dataSource"
             :pagination="false"
             rowKey="id"
             bordered>
      <template
          v-for="col in ['name']"
          :slot="col"
          slot-scope="text, record"
      >
        <div :key="col">
          <a-input
              v-if="record.id == editingKey"
              style="width: 200px"
              :value="text"
              @change="e => handleChange(e.target.value, record.id, col)"
          />
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
      <template slot="college" slot-scope="record">
        <template v-if="record.id == editingKey">
          <a-select
              showSearch
              :filter-option="filterOption"
              @change="selectChange(record.id, 'collegeId', collegeId)"
              style="width: 200px"
              v-model="collegeId"
              placeholder="请选择学院">
            <a-select-option
                v-for="college in colleges"
                :key="college.id"
                :value="college.id"
            >{{college.name}}</a-select-option>
          </a-select>
        </template>
        <span v-else v-text="collegeStr(record.collegeId)"></span>
      </template>
      <template slot="operation" slot-scope="text, record">
        <div class="editable-row-operations">
        <span v-if="record.id == editingKey">
          <a @click="() => save(record.id)">保存</a>
          <a-popconfirm title="确认取消?" @confirm="() => cancel(record.id)">
            <a>取消</a>
          </a-popconfirm>
        </span>
          <span v-else>
          <a :disabled="editingKey !== ''" @click="() => edit(record.id)">修改</a>
          <a-divider type="vertical" />
          <a-popconfirm title="确认删除?" @confirm="() => delGroup(record.id)">
            <a>删除</a>
          </a-popconfirm>
        </span>
        </div>
      </template>
    </a-table>
    <div class="pagination">
      <a-pagination
          v-model="pageParam.current"
          show-size-changer
          :page-size.sync="pageParam.pageSize"
          :total="pageParam.total"
          @showSizeChange="onShowSizeChange"
          @change="onPageChange"
      />
    </div>
    <groupForm ref="form" :colleges="colleges" @success="refreshData"/>
  </div>
</template>
<script>
import GroupForm from "@/pages/organization/group/components/GroupForm";
import {listGroupsByPage, editGroups, deleteGroups} from "@/services/groups";
import {totalCollege} from "@/services/college";

const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    scopedSlots: { customRender: 'id' },
  },
  {
    title: '教研室名称',
    dataIndex: 'name',
    scopedSlots: { customRender: 'name' },
  },
  {
    title: '所属学院',
    key: 'collegeId',
    scopedSlots: { customRender: 'college' },
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    scopedSlots: { customRender: 'createTime' },
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    scopedSlots: { customRender: 'updateTime' },
  },
  {
    title: '操作',
    dataIndex: 'operation',
    scopedSlots: { customRender: 'operation' },
  },
]

export default {
  components: { GroupForm },
  data() {
    return {
      pageParam :{
        pageSize: 10,
        current: 1,
        total: 200,
      },
      dataSource: [],
      cacheData: [],
      columns,
      colleges: [],
      collegeId: '',
      editingKey: '',
    };
  },

  methods: {
    delGroup(key){
      deleteGroups(key).then(res => {
        if (res.data.code == 200){
          this.refreshData()
        } else {
          this.$message.error = '删除失败'
        }
      })
    },
    handleChange(value, key, column) {
      const newData = this.dataSource;
      const target = newData.find(item => key === item.id);
      if (target) {
        target[column] = value;
        this.dataSource = newData;
      }
    },
    edit(key) {
      const newData = this.dataSource;
      const target = newData.find(item => key === item.id);
      if (target) {
        this.editingKey = key
        this.collegeId = target.collegeId
      }
    },
    save(key) {
      const newData = this.dataSource;
      const newCacheData = this.cacheData;
      const target = newData.find(item => key === item.id);
      const targetCache = newCacheData.find(item => key === item.id);
      if (target && targetCache) {
        editGroups(target).then(res => {
          if (res.data.code == 200){
            this.$message.success = "修改成功"
          } else {
            this.$message.error = '修改失败'
          }
        })
        Object.assign(targetCache, target);
        this.cacheData = newCacheData;
      }
      this.editingKey = '';
    },
    cancel(key) {
      const newData = this.dataSource;
      const target = newData.find(item => key === item.id);
      this.editingKey = '';
      if (target) {
        Object.assign(target, this.cacheData.find(item => key === item.id));
        this.data = newData;
      }
    },

    deployApplication() {
      this.$refs.form.dialog = true;
    },
    refreshData() {
      this.onPageChange(this.pageParam.current, this.pageParam.pageSize )
    },

    onShowSizeChange(current, pageSize) {
      listGroupsByPage(current, pageSize).then(this.afterChange)
    },
    onPageChange(page, pageSize) {
      listGroupsByPage(page, pageSize).then(this.afterChange)
    },
    afterChange(res) {
      const changeRes = res.data
      if (changeRes.code == 200){
        const pageRes = changeRes.data
        this.pageParam.current = pageRes.current
        this.pageParam.pageSize = pageRes.size
        this.pageParam.total = pageRes.total
        this.dataSource = pageRes.records
        this.cacheData = this.dataSource.map(item => ({ ...item }));
      } else {
        this.$message.error = changeRes.message
      }
    },
    listTotalCollege() {
      totalCollege().then(res => {
        const result = res.data
        if (result.code == 200) {
          this.colleges = result.data
        } else {
          this.$message.error(result.message)
        }
      })
    },
    collegeStr(id) {
      const colleges = this.colleges
      const college = colleges.find(item => item.id === id);
      return college.name
    },
    filterOption(input, option) {
      return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    selectChange(key, column, value) {
      console.log(key, column, value)
      const newData = this.dataSource;
      const target = newData.find(item => key === item.id);
      if (target) {
        target[column] = value;
        this.dataSource = newData;
        console.log(newData)
      }
    },
  },
  created() {
    this.refreshData()
    this.listTotalCollege()
  }
};
</script>
<style scoped>
.editable-row-operations a {
  margin-right: 8px;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

.my-btn {
  text-align: right;
  margin-right: 10px;
  margin-bottom: 10px;
}

</style>
